using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;

using NewtonDynamics;

namespace WPFPhysics1
{
	public class PolygonBody : Body
	{
		protected PointCollection points = new PointCollection();
		private static Random rand = new Random();

		public PolygonBody( CCollision collision, Vector[] vertices ) : base( collision, null )
		{
			foreach ( Vector vector in vertices )
			{
				points.Add( new System.Windows.Point( vector.X, vector.Y ) );
			}
		}

		/// <summary>
		/// Create vertex cloud from flat polygon
		/// </summary>
		/// <param name="vertices">Polygon vertices</param>
		/// <returns>Vertex cloud</returns>
		public static Vector3D[] CreateVertexCloud( IEnumerable<Vector> vertices, double depth )
		{
			List<Vector3D> cloud = new List<Vector3D>();

			foreach ( Vector vector in vertices )
			{
				cloud.Add( new Vector3D( vector.X, vector.Y, -depth / 2 ) );
				cloud.Add( new Vector3D( vector.X, vector.Y, depth / 2 ) );
			}

			return cloud.ToArray();
		}

		/// <summary>
		/// Create instance
		/// </summary>
		/// <param name="world">World</param>
		/// <param name="vertices">Vertices</param>
		/// <param name="depth">Depth</param>
		/// <returns>New instance</returns>
		public static PolygonBody Create( CWorld world, double mass, Vector[] vertices, double depth )
		{
			CCollisionConvexPrimitives collision = new CCollisionConvexPrimitives( world );
			collision.CreateConvexHull( CreateVertexCloud( vertices, depth ), Matrix3D.Identity );

			PolygonBody body = new PolygonBody( collision, vertices );

			InertialMatrix inertialMatrix = collision.CalculateInertialMatrix;

			body.MassMatrix = new MassMatrix( (float)mass, inertialMatrix.m_Inertia * mass );
			body.CentreOfMass = inertialMatrix.m_Origin;

			collision.Release();

			return body;
		}

		public PointCollection Points
		{
			get
			{
				return points;
			}
		}
	}
}